package com.liukai.personalbills.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.donkingliang.groupedadapter.adapter.GroupedRecyclerViewAdapter;
import com.donkingliang.groupedadapter.holder.BaseViewHolder;
import com.donkingliang.groupedadapter.widget.StickyHeaderLayout;
import com.liukai.personalbills.R;
import com.liukai.personalbills.activity.AddActivity;
import com.liukai.personalbills.activity.MainActivity;
import com.liukai.personalbills.adapter.BillsRecyclerAdapter;
import com.liukai.personalbills.bean.Account;
import com.liukai.personalbills.bean.AccountMessage;
import com.liukai.personalbills.bean.BillsBean;
import com.liukai.personalbills.bean.BillsTitleBean;
import com.liukai.personalbills.retrofitInterface.AccountAPI;
import com.liukai.personalbills.util.RetrofitManager;
import com.liukai.personalbills.util.TextUtil;
import com.liukai.personalbills.util.ToastUtil;

import org.w3c.dom.Text;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

public class BillsFragment extends Fragment implements View.OnClickListener {


    private RecyclerView recyclerView;
    private Context context;
    private ArrayList<BillsTitleBean> titleBeanArrayList;
    private BillsTitleBean billsTitleBean;
    private ArrayList<BillsBean> billsBeanArrayList;
    private BillsBean billsBean;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
//                addData((BillsBean)msg.obj);
            }else if(msg.what == 1){
                if(titleBeanArrayList != null){
                    titleBeanArrayList.removeAll(titleBeanArrayList);
                }
                getAllAccountFromServer();
            }
        }
    };


    private BillsTitleBean billsTitleBean1;
    private ArrayList<BillsBean> billsBeans;
    private BillsRecyclerAdapter billsRecyclerAdapter;

    @Nullable
    @Override
    public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_bills,null);
        context = getContext();

        initDate();
        initView(view);
        initListener();

        return view;
    }

    private void initDate(){

        titleBeanArrayList = new ArrayList<>();
        getAllAccountFromServer();
//        for(int i = 0;i < 19;i ++){
//            billsTitleBean = new BillsTitleBean();
//            billsTitleBean.setDate((2010+i)+"年"+(1+i)+"月"+(10+i)+"日");
//            billsTitleBean.setIncome(10000*(i+1)+"");
//            billsTitleBean.setExpend(5000*(i+1)+"");
//            billsBeanArrayList = new ArrayList<>();
//
//            for(int j = 0;j < 5;j ++){
//                billsBean = new BillsBean();
//                billsBean.setImgIcon(R.mipmap.salary);
//                billsBean.setType("工资");
//                billsBean.setMoney(1000*(j+1)+"");
//                billsBeanArrayList.add(billsBean);
//            }
//
//            billsTitleBean.setBillsBeanArrayList(billsBeanArrayList);
//            titleBeanArrayList.add(billsTitleBean);
//
//        }
//        billsTitleBean = new BillsTitleBean();
//        billsTitleBean.setDate("2019-1-1");
//        billsTitleBean.setIncome("1000");
//        billsTitleBean.setExpend("2000");
//
//        billsBeanArrayList = new ArrayList<>();
//        billsBean = new BillsBean();
//        billsBean.setImgIcon(R.mipmap.salary);
//        billsBean.setType("工资");
//        billsBean.setMoney("300");
//        billsBean.setTextColor(R.color.colorPrimaryDark);
//        billsBeanArrayList.add(billsBean);
//        billsTitleBean.setBillsBeanArrayList(billsBeanArrayList);
//        titleBeanArrayList.add(billsTitleBean);


    }

    private void initView(View view){

        recyclerView = view.findViewById(R.id.recyclerView);
        billsRecyclerAdapter = new BillsRecyclerAdapter(context,titleBeanArrayList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(billsRecyclerAdapter);

        StickyHeaderLayout stickyHeaderLayout = view.findViewById(R.id.stickyLayout);
        stickyHeaderLayout.setSticky(true);

    }

    private void initListener() {

        billsRecyclerAdapter.setOnChildClickListener((adapter, holder, groupPosition, childPosition) -> {

            BillsBean billsBean = titleBeanArrayList.get(groupPosition).getBillsBeanArrayList().get(childPosition);
            Intent intentAddActivity = new Intent(context,AddActivity.class);
            ToastUtil.log(context,"BillsFragment",billsBean.toString());
            intentAddActivity.putExtra("billsBean",billsBean);
            startActivity(intentAddActivity);

        });

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){



        }


    }


    private boolean addData(BillsBean _billsBean){
//        String date = billsBean.getDate();
//        String type = billsBean.getType();
//        int imgIcon = billsBean.getImgIcon();
//        String remark = billsBean.getRemark();
//        String money = billsBean.getMoney();
//        BillsTitleBean billsTitleBean0 = new BillsTitleBean();
//
//        for(int i = 0;i < titleBeanArrayList.size();i ++){
//            billsTitleBean1 = titleBeanArrayList.get(i);
//            String date0 = billsTitleBean1.getDate();
//            String income = billsTitleBean1.getIncome();
//            String expand = billsTitleBean1.getExpend();
//            billsBeans = billsTitleBean1.getBillsBeanArrayList();
//            if(date0.equals(date)){
//                titleBeanArrayList.remove(i);
//                billsTitleBean1.setDate(date);
//                if (isIncome(type)){
//                    billsTitleBean1.setIncome(String.valueOf(Integer.parseInt(income.trim()) + Integer.parseInt(money.trim())));
//                    billsTitleBean1.setExpend(expand);
//                }else{
//                    billsTitleBean1.setExpend(String.valueOf(Integer.parseInt(expand.trim()) + Integer.parseInt(money.trim())));
//                    billsTitleBean1.setIncome(income);
//                }
//                billsBeans.add(billsBean);
//                billsTitleBean1.setBillsBeanArrayList(billsBeans);
//                titleBeanArrayList.add(i,billsTitleBean1);
//                billsRecyclerAdapter.notifyItemInserted(i);
//                break;
//            }else{
//                billsTitleBean1 = new BillsTitleBean();
//                billsTitleBean1.setDate(date);
//                if (isIncome(type)){
//                    billsTitleBean1.setIncome(String.valueOf(Integer.parseInt(income.trim()) + Integer.parseInt(money.trim())));
//                }else{
//                    billsTitleBean1.setExpend(String.valueOf(Integer.parseInt(expand.trim()) + Integer.parseInt(money.trim())));
//                }
//                billsBeans.add(billsBean);
//                billsTitleBean1.setBillsBeanArrayList(billsBeans);
//                titleBeanArrayList.add(billsTitleBean1);
//                billsRecyclerAdapter.notifyItemInserted(i);
//                break;
//            }
//
//        }

        String newDate = _billsBean.getDate();

        for(int i = 0;i < titleBeanArrayList.size();i ++){
            billsTitleBean1 = titleBeanArrayList.get(i);
            String oldDate = billsTitleBean1.getDate();
            if(newDate.equals(oldDate)){// 判断新增的日期在原来的数据中是否存在
                // 存在
                addbills(billsTitleBean1,_billsBean);
                billsRecyclerAdapter.notifyDataSetChanged();
                return true;
            }
        }

        titleBeanArrayList.add(addTitle(_billsBean));// 新增一个日期和数据
        billsRecyclerAdapter.notifyDataSetChanged();
        return false;

    }


    /**
     * 刷新所有账单
     * @param accounts
     */
    private void updateData(List<Account> accounts) {

//        ToastUtil.log(getContext(),"accounts",accounts.toString());

        for(int i = 0;i < accounts.size();i ++){

            Account account = accounts.get(i);
            BillsBean billsBean = new BillsBean();
            billsBean.setDate(account.getDate());
            billsBean.setMoney(account.getMoney());
            billsBean.setType(account.getType());
            billsBean.setRemark(account.getRemark());
            billsBean.setTimeId(account.getTimeId());
            // 根据消费类别获取消费类别图标
            billsBean.setImgIcon(TextUtil.getNullIcon(account.getType()));
            ToastUtil.log(context,"updateBills",billsBean.getTimeId());
            addData(billsBean);

        }

    }


    /**
     * 新增一个日期和数据
     * @param billsBean
     * @return
     */
    private BillsTitleBean addTitle(BillsBean billsBean){
        BillsTitleBean billsTitleBean = new BillsTitleBean();
        if(TextUtil.isIncome(billsBean.getType())){// 判断数据是支出还是收入
            // 收入
            billsTitleBean.setIncome(billsBean.getMoney()+"");
            billsTitleBean.setExpend("0");
        }else{
            // 支出
            billsTitleBean.setExpend(billsBean.getMoney()+"");
            billsTitleBean.setIncome("0");
        }
        billsTitleBean.setDate(billsBean.getDate());
        ArrayList<BillsBean> billsBeans = new ArrayList<>();
        billsBeans.add(billsBean);
        billsTitleBean.setBillsBeanArrayList(billsBeans);
        ToastUtil.log(context,"titleBean",billsTitleBean.toString());
        return billsTitleBean;
    }

    private void addbills(BillsTitleBean billsTitleBean1,BillsBean _billsBean){

        String income = billsTitleBean1.getIncome();
        String expend = billsTitleBean1.getExpend();
        if(TextUtil.isIncome(_billsBean.getType())){//判断数据是支出还是收入
            // 修改支出金额
            billsTitleBean1.setIncome(String.valueOf(Double.parseDouble(_billsBean.getMoney()) + Double.parseDouble(income)));
        }else{
            // 修改收入金额
            billsTitleBean1.setExpend(String.valueOf(Double.parseDouble(_billsBean.getMoney()) + Double.parseDouble(expend)));
        }
        ToastUtil.log(context,"addbills",_billsBean.getTimeId());
        ArrayList<BillsBean> billsBeans1 = billsTitleBean1.getBillsBeanArrayList();
        billsBeans1.add(_billsBean);
        billsTitleBean1.setBillsBeanArrayList(billsBeans1);
    }

    /**
     * 将handler对象传递给MainActivity
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        MainActivity mainActivity = (MainActivity)context;
        mainActivity.setHandler(handler);
    }

    private void getAllAccountFromServer(){

        String username = TextUtil.username;

        if(username != null){
            AccountAPI accountAPI = RetrofitManager.getAccountAPI();
            Call<AccountMessage> findAllTask = accountAPI.findAll(username);
            findAllTask.enqueue(new Callback<AccountMessage>() {
                @Override
                public void onResponse(Call<AccountMessage> call, Response<AccountMessage> response) {
                    int code = response.code();
                    if(code == HttpURLConnection.HTTP_OK){
                        AccountMessage body = response.body();

//                    ToastUtil.log(context,"onResponse",response.body().toString());

                        List<Account> accounts = body.getData();
                        ToastUtil.log(context,"account",body.toString());
                        String resultCode = body.getCode();
                        if(resultCode.equals(TextUtil.CODE_OK)){
                            // TODO: 数据查询成功
                            updateData(accounts);
                        }else{
                            //TODO: 数据查询失败
                        }
                        ToastUtil.show(context,resultCode);
                    }else{
                        ToastUtil.show(context,"错误:" + code);
                    }
                }

                @Override
                public void onFailure(Call<AccountMessage> call, Throwable t) {
                    ToastUtil.show(context,"请求失败，请检查网络是否连接");
                    ToastUtil.log(context,"onFailure",t.toString());
                }
            });

        }
    }

}
